package com.raa.core;

import com.raa.log.LoggerProvider;

import java.util.LinkedList;
import java.util.logging.Logger;

public class Role {

	private static Logger logger = LoggerProvider.provide(Role.class);

	private String name;

	private LinkedList<Validator> validators;

	public Role (String name) {
		this.name = name;
		this.validators = new LinkedList<>( );
	}

	public void clear() {
		this.validators.clear();
	}

	public Role addValidator (Validator validator) {
		this.validators.add(validator);
		logger.info("为角色 [" + this.name + "] 添加验证器: \"" + validator.getClass( ).getSimpleName( ) + "\"");
		return this;
	}

	public String getName ( ) {
		return name;
	}

	@SuppressWarnings("unchecked")
	public Object validate (Object object, ActionTable actionTable) {
		ObjectWrapper wrapper = new ObjectWrapper(object);
		String id = wrapper.getValidateId(actionTable, null);
		logger.info(String.format("校验流水号 [%s]\n检查对象 [%s@%s] 是否属于角色 [%s]，行为表: [%s]",
				id,
				object.getClass().getSimpleName(),
				object.hashCode(),
				this.name,
				actionTable.getClass().getSimpleName()));
		for (Validator validator : this.validators) {
			try {
				logger.info(String.format("校验流水号 [%s]\n 使用校验器: %s",
						wrapper.getValidateId(actionTable, validator), validator.getClass().getSimpleName()));
				if (! validator.validate(object))
					return actionTable.happen(wrapper, validator.errCode(), object, validator, null);
			} catch (Exception e) {
				return actionTable.happen(wrapper, ActionTable.State.Crash, object, validator, e);
			}
		}
		return actionTable.happen(wrapper, ActionTable.State.Success, object, null, null);
	}

}
